np.random.seed(42)
df_price = pd.DataFrame({
'日期': pd.date_range('2024-01-01', periods=60),
'收盘价': 100 + np.cumsum(np.random.normal(0.5, 2, 60))
})
# 计算移动平均线
df_price['MA5'] = df_price['收盘价'].rolling(window=5).mean()
df_price['MA20'] = df_price['收盘价'].rolling(window=20).mean()
plt.figure(figsize=(14, 7))
plt.plot(df_price['日期'], df_price['收盘价'],
label='收盘价', linewidth=1.5, color='#2C3E50', alpha=0.7)
plt.plot(df_price['日期'], df_price['MA5'],
label='MA5', linewidth=1.5, color='#E3120B')
plt.plot(df_price['日期'], df_price['MA20'],
label='MA20', linewidth=1.5, color='#008080')
# 标注金叉和死叉
golden_cross = (df_price['MA5'] > df_price['MA20']) & \
(df_price['MA5'].shift(1) <= df_price['MA20'].shift(1))
death_cross = (df_price['MA5'] < df_price['MA20']) & \
(df_price['MA5'].shift(1) >= df_price['MA20'].shift(1))
plt.scatter(df_price['日期'][golden_cross], df_price['MA5'][golden_cross],
color='red', s=100, marker='^', label='金叉', zorder=5)
plt.scatter(df_price['日期'][death_cross], df_price['MA5'][death_cross],
color='green', s=100, marker='v', label='死叉', zorder=5)
plt.title('移动平均线与交叉信号', fontsize=16, fontweight='bold')
plt.xlabel('日期', fontsize=12)
plt.ylabel('价格(元)', fontsize=12)
plt.legend(loc='best', fontsize=11)
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()